package org.inspiration.dudu.common.util;

import org.inspiration.dudu.common.constant.Constant;
import org.inspiration.dudu.common.exception.ServiceException;
import org.springframework.beans.factory.annotation.Value;

import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;

@Component
public class FileUtil {
    @Value("${dudu.file.upload-path}")
    private String uploadPath;
    @Value("${dudu.url-prefix}")
    private String urlPrefix;

    /**
     * 上传图片、视频等文件
     * 把文件存到对应路径的文件系统
     * D:\\www\\dudu\\ + images\\UUID.xx
     *
     * @param file
     * @param subPath
     * @return
     */

    public void upload(MultipartFile file, Path subPath) {
        if (file.isEmpty()) {
            throw new ServiceException(Constant.FILE_IS_EMPTY);
        }
        Path path = Paths.get(uploadPath).resolve(subPath);

        // 创建目录（如果不存在）
        try {
            Files.createDirectories(path.getParent());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        //保存文件
        try {
            file.transferTo(path);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    public String uploadImage(MultipartFile file) {
        String uuid = UUID.randomUUID().toString();
        String fileExtension = FileUtil.getFileExtension(file);
        //Filename UUID.xxx
        String filename = uuid + "." + fileExtension;
        //获取文件存储路径：D:\\www\\dudu\\ + images\\UUID.xx;
        Path subPath = Paths.get("images", filename);
        // 调用文件工具存入文件系统
        upload(file, subPath);
        //http://localhost:8080/download/ + image/UUID.xx
        return urlPrefix + "image/" + filename;
    }

    /**
     * 将文本写入文件
     *
     * @param content
     * @param subPath
     */
    public void upload(String content, Path subPath) {

        Path path = Paths.get(uploadPath).resolve(subPath);

        // 创建目录（如果不存在）
        try {
            Files.createDirectories(path.getParent());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        //保存文件
        try {
            Files.writeString(path, content);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    /**
     * 获取文件扩展名
     *
     * @param file
     * @return
     */
    public static String getFileExtension(MultipartFile file) {
        String originalFilename = file.getOriginalFilename();
        if (originalFilename != null) {
            int lastIndex = originalFilename.lastIndexOf('.');
            if (lastIndex != -1) {
                return originalFilename.substring(lastIndex + 1);
            }
        }
        return "";
    }

    public static String readStringFromFile(String filePath) {
        try {
            return new String(Files.readAllBytes(Paths.get(filePath)));
        } catch (IOException e) {
            throw new ServiceException("读取文件时发生错误: " + e.getMessage());
        }
    }


}
